/*
 * srav.cc
 *
 *  Created on: 07/10/2008
 *      Author: Flavio S Truzzi
 */

#include "cv.h"
#include "highgui.h"
#include "srav.h"

void preprocess_threshold(IplImage *src, IplImage *Y, IplImage *Ytmp, IplImage *Cb, IplImage *Cbtmp, IplImage *Cr, IplImage *Crtmp){
  cvCvtColor(src,src,CV_RGB2YCrCb);

  cvSplit(src, Y, Cb, Cr, NULL);
  cvSplit(src, Ytmp, Cbtmp, Crtmp, NULL);
}


void skin_threshold(IplImage *src, IplImage *ddst,IplConvKernel *the_elem, IplImage *Y,IplImage *Ytmp,int Ymaxthreshold, int Yminthreshold, IplImage *Cb, IplImage *Cbtmp, int CBmaxthreshold, int CBminthreshold, IplImage *Cr, IplImage *Crtmp, int CRmaxthreshold, int CRminthreshold, int KINDOF)
{
  IplImage *dst_mul;
  IplImage *dst_mor;

  CvSize size = cvGetSize(src);

  dst_mul = cvCreateImage(size, 8, 1);
  dst_mor = cvCreateImage(size, 8, 1);

  cvThreshold(Y, Ytmp, Ymaxthreshold, 255, CV_THRESH_TOZERO_INV);
  cvThreshold(Ytmp, Ytmp, Yminthreshold, 255, CV_THRESH_BINARY );
  cvThreshold(Cb, Cbtmp, CBmaxthreshold, 255, CV_THRESH_TOZERO_INV );
  cvThreshold(Cbtmp, Cbtmp, CBminthreshold, 255, CV_THRESH_BINARY );
  cvThreshold(Cr, Crtmp, CRmaxthreshold, 255, CV_THRESH_TOZERO_INV );
  cvThreshold(Crtmp, Crtmp, CRminthreshold, 255, CV_THRESH_BINARY );
  //  cvMerge( Ytmp, Cbtmp, Crtmp, NULL, dst );
   cvMul(Ytmp, Cbtmp, dst_mul);
   cvMul(dst_mul, Crtmp, dst_mul);
   the_elem = cvCreateStructuringElementEx( 5, 5, 3, 3, CV_SHAPE_ELLIPSE);///ELLIPSE
   cvErode(dst_mul, dst_mor, the_elem);
   cvDilate(dst_mor, dst_mor, the_elem);
   cvDilate(dst_mor, dst_mor, the_elem);
   cvErode(dst_mor, dst_mor, the_elem);
  // cvDilate(dst_mor, dst_mor, the_elem);

   switch (KINDOF)
     {
       //    case DST:
       //      cvConvertScale(dst, ddst, 1, 0);
       //      break;
     case DST_MUL:
       cvConvertScale(dst_mul, ddst, 1, 0);
       break;
     case DST_MOR:
       cvConvertScale(dst_mor, ddst, 1, 0);
       break;
       }

     cvReleaseImage(&dst_mul);
     cvReleaseImage(&dst_mor);
   }
